package interviewClassic150;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

public class IsHappy {
    public boolean isHappy(int n) {
        //定义一个set，来存放已经有的数字
        Set<Integer> set = new HashSet<>();
        while (!set.contains(n)) {
            //不存在这个值，则将值添加到set中
            //System.out.println(n);
            set.add(n);
            n = convert(n);
        }
        return n == 1;
    }

    private int convert(int n) {
        int res = 0;
        while (n != 0) {
            int cur = n % 10;
            res += cur * cur;
            n = n / 10;
        }
        return res;
    }

    @Test
    public void test() {
        System.out.println(isHappy(2));
    }
}
